package cn.gcxy.petstore.dao.impl;

import cn.gcxy.base.db.ConnectionHandler;
import cn.gcxy.base.exception.NotExistException;
import cn.gcxy.petstore.dao.IPersonDAO;
import cn.gcxy.petstore.model.Person;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.sql.ResultSet;

public class PersonDAOImpl implements IPersonDAO {

    @Override
    public boolean UpdataPerson(Person person) throws  Exception {
        PreparedStatement pre = null;
        try{
            pre = ConnectionHandler.getConnection().prepareStatement
                    ("update person set name = ?"+",balance = ?"+",password = ?"+"where id = ?");
            pre.setString(1,person.getName());
            pre.setInt(2,person.getBalance());
            pre.setString(3,person.getPassword());
            pre.setInt(4,person.getId());
            int num = pre.executeUpdate();
            if(num != 1){
                throw new NotExistException();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ConnectionHandler.close(pre);
        }
        return true;
    }

    @Override
    public ArrayList<Person> FindAllPerson() throws SQLException {
        ArrayList<Person> people = new ArrayList<Person>();
        PreparedStatement pre = null;
        ResultSet res = null;
        try{
            pre = ConnectionHandler.getConnection().prepareStatement("select * from person");
            res= pre.executeQuery();
            while(res.next()){
                Person person = new Person();
                person.setId(res.getInt("id"));
                person.setName(res.getString("name"));
                person.setPassword(res.getString("password"));
                person.setBalance(res.getInt("balance"));
                people.add(person);}

        }catch (SQLException e) {
            e.printStackTrace();
        }finally {
            ConnectionHandler.close(res,pre);
        }
        return people;
    }

    @Override
    public Person FindPersonById(int id) throws SQLException {
        Person person = null;
        PreparedStatement pre = null;
        ResultSet res = null;
        try{
            pre = ConnectionHandler.getConnection().prepareStatement
                    ("select * from person where id = ?");
            pre.setInt(1,id);
            res = pre.executeQuery();
            if (res.next()){
                person = new Person();
                person.setId(res.getInt("id"));
                person.setName(res.getString("name"));
                person.setPassword(res.getString("password"));
                person.setBalance(res.getInt("balance"));
            }
        }catch(SQLException e){
            e.printStackTrace();
        }finally {
            ConnectionHandler.close(res,pre);
        }
        return person;
    }
}
